package cn.iocoder.yudao.module.contract.service.frameworkAgreement;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.module.contract.dal.dataobject.client.ClientDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.company.CompanyDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.contractTemplate.ContractTemplateDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.contractType.ContractTypeDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.invoiceContract.InvoiceContractDO;
import cn.iocoder.yudao.module.contract.dal.dataobject.orderContract.OrderContractDO;
import cn.iocoder.yudao.module.contract.dal.mysql.client.ClientMapper;
import cn.iocoder.yudao.module.contract.dal.mysql.company.CompanyMapper;
import cn.iocoder.yudao.module.contract.dal.mysql.contractTemplate.ContractTemplateMapper;
import cn.iocoder.yudao.module.contract.dal.mysql.invoice.InvoiceMapper;
import cn.iocoder.yudao.module.contract.dal.mysql.invoiceContract.InvoiceContractMapper;
import cn.iocoder.yudao.module.contract.dal.mysql.orderContract.OrderContractMapper;
import cn.iocoder.yudao.module.contract.service.dataIndex.DataIndexService;
import cn.iocoder.yudao.module.contract.utils.HtmlToFileConverter;
import cn.iocoder.yudao.module.contract.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.annotations.VisibleForTesting;
import lombok.Synchronized;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Entities;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.IntStream;

import cn.iocoder.yudao.module.contract.controller.admin.frameworkAgreement.vo.*;
import cn.iocoder.yudao.module.contract.dal.dataobject.frameworkAgreement.FrameworkAgreementDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.contract.dal.mysql.frameworkAgreement.FrameworkAgreementMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.contract.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_IMPORT_LIST_IS_EMPTY;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_USERNAME_EXISTS;

/**
 * 框架协议 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class FrameworkAgreementServiceImpl extends ServiceImpl<FrameworkAgreementMapper, FrameworkAgreementDO> implements FrameworkAgreementService {

    @Resource
    private FrameworkAgreementMapper frameworkAgreementMapper;
    @Resource
    private ContractTemplateMapper contractTemplateMapper;
    @Resource
    private ClientMapper clientMapper;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private HtmlToFileConverter htmlToFileConverter;
    @Resource
    private DataIndexService dataIndexService;
    @Resource
    private InvoiceContractMapper invoiceContractMapper;
    @Resource
    private OrderContractMapper orderContractMapper;

    @Override
    @Synchronized
    public Long createFrameworkAgreement(FrameworkAgreementSaveReqVO createReqVO) {
        if(DateUtil.parse(createReqVO.getAgreementStartDate(),"yyyy-MM-dd").getTime()>DateUtil.parse(createReqVO.getAgreementEndDate(),"yyyy-MM-dd").getTime()){
            throw exception("有效期开始时间不能大于结束时间");
        }
        //校验唯一
//        validateUnique(createReqVO.getId(),createReqVO.getContractNo());
        // 插入
        FrameworkAgreementDO frameworkAgreement = BeanUtils.toBean(createReqVO, FrameworkAgreementDO.class);
        ContractTemplateDO contractTemplate = contractTemplateMapper.selectById(frameworkAgreement.getContractTemplateId());
        frameworkAgreement.setContractTemplateName(contractTemplate.getContractName());
        ClientDO clientDO = clientMapper.selectById(frameworkAgreement.getClientId());
        frameworkAgreement.setClientName(clientDO.getClientName());
        frameworkAgreement.setClientCode(clientDO.getClientCode());
        frameworkAgreement.setClientInfo(JSONObject.toJSONString(clientDO));
        validateUnique(frameworkAgreement.getId(),frameworkAgreement.getClientName(),frameworkAgreement.getAgreementStartDate(),frameworkAgreement.getAgreementEndDate());
//        long count = contractTemplateMapper.countByYear(createReqVO.getAgreementStartDate());
        long count = dataIndexService.getValue("KJXY_"+createReqVO.getAgreementStartDate().substring(0,4));
        String contractNo = "KJ-"+(createReqVO.getAgreementStartDate().substring(2,4))+sequenceCode(10000, count+1);
        if(StringUtils.isBlank(frameworkAgreement.getContractNo())){
            frameworkAgreement.setContractNo(contractNo);
        }
        validateUnique(frameworkAgreement.getId(),frameworkAgreement.getContractNo());
        //生成合同文件
        generateContractFile(frameworkAgreement);
        dataIndexService.updateValue("KJXY_"+createReqVO.getAgreementStartDate().substring(0,4),count+1);
        frameworkAgreementMapper.insert(frameworkAgreement);
        // 返回
        return frameworkAgreement.getId();
    }

    @Override
    public void updateFrameworkAgreement(FrameworkAgreementSaveReqVO updateReqVO) {
        if(DateUtil.parse(updateReqVO.getAgreementStartDate(),"yyyy-MM-dd").getTime()>DateUtil.parse(updateReqVO.getAgreementEndDate(),"yyyy-MM-dd").getTime()){
            throw exception("有效期开始时间不能大于结束时间");
        }
        //校验唯一
        validateUnique(updateReqVO.getId(),updateReqVO.getContractNo());
        // 校验存在
        validateFrameworkAgreementExists(updateReqVO.getId());
        // 更新
        FrameworkAgreementDO frameworkAgreement = BeanUtils.toBean(updateReqVO, FrameworkAgreementDO.class);
        ContractTemplateDO contractTemplate = contractTemplateMapper.selectById(frameworkAgreement.getContractTemplateId());
        frameworkAgreement.setContractTemplateName(contractTemplate.getContractName());
        ClientDO clientDO = clientMapper.selectById(frameworkAgreement.getClientId());
        frameworkAgreement.setClientName(clientDO.getClientName());
        frameworkAgreement.setClientCode(clientDO.getClientCode());
        frameworkAgreement.setClientInfo(JSONObject.toJSONString(clientDO));
        validateUnique(frameworkAgreement.getId(),frameworkAgreement.getClientName(),frameworkAgreement.getAgreementStartDate(),frameworkAgreement.getAgreementEndDate());
        //生成合同文件
        generateContractFile(frameworkAgreement);
        frameworkAgreementMapper.updateById(frameworkAgreement);
    }

    @Override
    public void deleteFrameworkAgreement(Long id) {
        OrderContractDO contractDO = orderContractMapper.selectOne(new LambdaQueryWrapper<OrderContractDO>().eq(OrderContractDO::getFrameworkAgreementId,id),false);
        if(contractDO!=null){
            throw exception("框架协议已被销购合同使用无法删除");
        }

        InvoiceContractDO invoiceContractDO = invoiceContractMapper.selectOne(new LambdaQueryWrapper<InvoiceContractDO>().eq(InvoiceContractDO::getFrameworkAgreementId,id).ne(InvoiceContractDO::getStatus,"2"),false);
        if(invoiceContractDO!=null){
            throw exception("框架协议已被发票合同使用无法删除");
        }
        // 校验存在
        validateFrameworkAgreementExists(id);
        // 删除
        frameworkAgreementMapper.deleteById(id);
    }

    private void validateFrameworkAgreementExists(Long id) {
        if (frameworkAgreementMapper.selectById(id) == null) {
            throw exception(FRAMEWORK_AGREEMENT_NOT_EXISTS);
        }
    }

    @VisibleForTesting
    void validateUnique(Long id, String contractNo) {
        if (StrUtil.isBlank(contractNo)) {
            return;
        }
        FrameworkAgreementDO data = frameworkAgreementMapper.selectOne(new LambdaQueryWrapper<FrameworkAgreementDO>().eq(FrameworkAgreementDO::getContractNo,contractNo));
        if (data == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (id == null) {
            throw exception(FRAMEWORK_AGREEMENT_EXISTS);
        }
        if (!data.getId().equals(id)) {
            throw exception(FRAMEWORK_AGREEMENT_EXISTS);
        }
    }

    @VisibleForTesting
    void validateUnique(Long id, String clientName,String agreementStartDate,String agreementEndDate) {

        int count = frameworkAgreementMapper.countClientDate(id,clientName,agreementStartDate,agreementEndDate);

        // 如果 id 为空，说明不用比较是否为相同 id 的用户
        if (count>0) {
            throw exception(FRAMEWORK_AGREEMENT_CLIENT_EXISTS);
        }

    }

    @VisibleForTesting
    void validateImport(FrameworkAgreementImportExcelVO data) {
        if(StringUtils.isBlank(data.getContractTypeCode())){
            throw exception("合同类型必填");
        }
        if(StringUtils.isBlank(data.getClientName())){
            throw exception("客户名称必填");
        }
        if(StringUtils.isBlank(data.getCompanyPersonName())){
            throw exception("公司人员姓名必填");
        }
        if(StringUtils.isBlank(data.getCompanyPersonJob())){
            throw exception("公司人员职务必填");
        }
        if(StringUtils.isBlank(data.getCompanyPersonContactWay())){
            throw exception("公司人员联系方式必填");
        }
        if(StringUtils.isBlank(data.getAgreementStartDate())){
            throw exception("协议有效开始日期必填");
        }
        if(StringUtils.isBlank(data.getAgreementEndDate())){
            throw exception("协议有效结束日期必填");
        }
        if(StringUtils.isBlank(data.getSalesDept())){
            throw exception("销售部门必填");
        }
        if(StringUtils.isBlank(data.getCompanyNames())){
            throw exception("公司名称必填");
        }
        if(StringUtils.isBlank(data.getProductGroup())){
            throw exception("产品组必填");
        }

        try{
           Date agreementStartDate = DateUtils.parse(data.getAgreementStartDate(),"yyyy-MM-dd,yyyy-M-d,yyyy/MM/dd,yyyy/M/d");
           data.setAgreementStartDate(DateUtil.formatDate(agreementStartDate));
        }catch (DateException e){
            throw exception("协议有效期开始日期格式异常");
        }
        try{
            Date agreementEndDate = DateUtils.parse(data.getAgreementEndDate(),"yyyy-MM-dd,yyyy-M-d,yyyy/MM/dd,yyyy/M/d");
            data.setAgreementEndDate(DateUtil.formatDate(agreementEndDate));
        }catch (DateException e){
            throw exception("协议有效结束日期格式异常");
        }

    }

    @Override
    public FrameworkAgreementDO getFrameworkAgreement(Long id) {
        return frameworkAgreementMapper.selectById(id);
    }

    @Override
    public PageResult<FrameworkAgreementRespVO> getFrameworkAgreementPage(FrameworkAgreementPageReqVO pageReqVO) {
        return frameworkAgreementMapper.selectPage(pageReqVO);
    }

    @Override
    public void generateContractFile(FrameworkAgreementDO frameworkAgreementDO) {
        ContractTemplateDO contractTemplate = contractTemplateMapper.selectById(frameworkAgreementDO.getContractTemplateId());
        if(contractTemplate ==null){
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"合同模板不存在");
        }
        try{
            String htmlContent = contractTemplate.getContractContent();
            htmlContent = htmlInit(htmlContent);
            Map<String,Object> param = buildContractParam(frameworkAgreementDO);
            htmlContent = HtmlToFileConverter.authHtmlToPdf(htmlContent, param);
            String fileUrl = htmlToFileConverter.htmlToWord(htmlContent,"contract/"+frameworkAgreementDO.getContractNo(),"ht-");
//            String fileUrl = htmlToFileConverter.htmlToPdf(htmlContent,"contract/"+frameworkAgreementDO.getContractNo());
            frameworkAgreementDO.setContractHtml(htmlContent);
            frameworkAgreementDO.setContractFileUrl(fileUrl);
        }catch (Exception e){
            log.error("合同生成异常"+e);
            throw new ServiceException(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(),"合同生成异常");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public FrameworkAgreementImportRespVO importList(List<FrameworkAgreementImportExcelVO> importUsers, Boolean isUpdateSupport) {
            if (CollUtil.isEmpty(importUsers)) {
                throw exception(USER_IMPORT_LIST_IS_EMPTY);
            }
        FrameworkAgreementImportRespVO respVO = FrameworkAgreementImportRespVO.builder().createUsernames(new ArrayList<>())
                    .updateUsernames(new ArrayList<>()).failureUsernames(new LinkedHashMap<>()).build();
        IntStream.range(0, importUsers.size()).forEach(index -> {
            FrameworkAgreementImportExcelVO importData = importUsers.get(index);
                // 校验，判断是否有不符合的原因
                try {
                    validateImport(importData);
                    FrameworkAgreementSaveReqVO createReqVO = BeanUtils.toBean(importData, FrameworkAgreementSaveReqVO.class);
                    ClientDO clientDO = clientMapper.selectOne(new LambdaQueryWrapper<ClientDO>().eq(ClientDO::getClientName,importData.getClientName()),false);
                    if(clientDO==null){
                        throw exception("客户："+importData.getClientName()+"不存在");
                    }
                    String [] companyNames = importData.getCompanyNames().split(",");
                    for(String companyName : companyNames){
                        long count = companyMapper.selectCount(new LambdaQueryWrapper<CompanyDO>().eq(CompanyDO::getCompanyName,companyName));
                        if(count<1){
                            throw exception("公司："+companyName+"不存在");
                        }
                    }
                    createReqVO.setClientId(clientDO.getId());
                    ContractTemplateDO contractTemplate = contractTemplateMapper.selectOne(new LambdaQueryWrapper<ContractTemplateDO>().eq(ContractTemplateDO::getContractTypeCode,importData.getContractTypeCode()).like(ContractTemplateDO::getContractTypeName,"框架协议"),false);
                    if(contractTemplate==null){
                        throw exception("框架协议合同类型"+importData.getContractTypeCode()+"不存在");
                    }
                    createReqVO.setContractTemplateId(contractTemplate.getId());
                    createFrameworkAgreement(createReqVO);
                } catch (ServiceException ex) {
                    respVO.getFailureUsernames().put("第"+(index+2)+"行-", ex.getMessage());
                    return;
                } catch (DateException e) {
                    respVO.getFailureUsernames().put("第"+(index+2)+"行-","时间格式异常，请按yyyy-MM-dd格式");
                    return;
                }
                respVO.getCreateUsernames().add("第"+(index+2)+"行-"+importData.getClientName());
            });
            return respVO;
    }

    /**
     * 处理富文本html
     * @param htmlContent
     * @return
     */
    private String htmlInit(String htmlContent) {
//        htmlContent = addWatermark(htmlContent);
        Document doc = Jsoup.parse(htmlContent);
//        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
//        doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
        Elements tdElements =  doc.select("td");
        for (Element cell : tdElements) {
            String text = cell.text(); // 获取td元素及其所有子元素的文本内容
            if (text.startsWith("${orderInfo")) {
                Element tr = cell.parent(); // 获取单元格的父元素
                if (tr.tagName().equals("tr")) { // 确保父元素是tr
                    Element trr = tr.parent(); // 获取单元格的父元素
                    if(!trr.tagName().equals("list")) {
                        // 创建<#list></#list>元素
                        tr.wrap("<list>");
                    }
                }
            }
        }

        htmlContent = doc.html();
        htmlContent = htmlContent.replaceAll("<list>","<#list orderList as orderInfo>");
        htmlContent = htmlContent.replaceAll("</list>","</#list>");
        return htmlContent;
    }
    private String addWatermark(String htmlContent){
        return "<html><head></head><body><div class='contract-pages'>"+htmlContent+"<div class='watermark'></div></div></body><style>.contract-pages>.watermark::before{content:'';position:absolute;width:100%;height:120%;top:-0%;left:-0%;background-position:00;background-origin:content-box;background-attachment:scroll;transform:rotate(0deg);background-size:auto;background-repeat:round;opacity:0.6;pointer-events:none;background-image:url(\"\");/*水印图片*/}</style></html>";
    }

    /**
     * 构建合同变量参数
     * @return
     */
    private Map<String,Object> buildContractParam(FrameworkAgreementDO frameworkAgreementDO){
        Map<String,Object> param = new HashMap<>();
        ClientDO clientDO = JSON.parseObject(frameworkAgreementDO.getClientInfo(),ClientDO.class);
        //框架协议专用
        param.put("合同编号", StringUtils.nvl(frameworkAgreementDO.getContractNo(), ""));
        param.put("乙方人员姓名",StringUtils.nvl(frameworkAgreementDO.getCompanyPersonName(), ""));
        param.put("乙方人员职务",StringUtils.nvl(frameworkAgreementDO.getCompanyPersonJob(), ""));
        param.put("乙方人员联系方式", StringUtils.nvl(frameworkAgreementDO.getCompanyPersonContactWay(), ""));
        param.put("协议有效期开始日期",StringUtils.nvl(frameworkAgreementDO.getAgreementStartDate(), ""));
        param.put("协议有效期结束日期",StringUtils.nvl(frameworkAgreementDO.getAgreementEndDate(), ""));
        param.put("协定账期月份",StringUtils.nvl(frameworkAgreementDO.getAccountPeriodMonth(), ""));
        param.put("结款月份",StringUtils.nvl(frameworkAgreementDO.getPaymentMonth(), ""));
        String productGroup = frameworkAgreementDO.getProductGroup();
        if(StringUtils.isNotBlank(frameworkAgreementDO.getProductGroup())){
            productGroup = frameworkAgreementDO.getProductGroup().replaceAll(",","、");
        }
        param.put("产品组",StringUtils.nvl(productGroup, ""));
//        StringBuilder companyNames = new StringBuilder();
//        StringBuilder companySigns = new StringBuilder();
//        if(StringUtils.isNotBlank(frameworkAgreementDO.getCompanyNames())){
//            String company = "<span style=\"margin-top: 1em;display: inline-block;width: 260pt;\">乙方（卖方{}）：<u><span>&nbsp;{}&nbsp;</span></u></span>";
//            String companySign = "<p class=\"MsoNormal\" style=\"line-height: 150%;display: inline-block;min-width: 260pt;max-width: 270pt;\"><span style=\"font-family: 黑体;/* line-height: 150%; */font-size: 9.5pt;text-align: center;\">乙方（卖方{}）： <u><span>&nbsp;{}&nbsp;</span></u> <br> <span style=\"display: flex;justify-content: center;align-items: center;margin: 60pt 0;\">(合同章)</span></span>  </p>";
//            companyNames.append("<span style=\"width: 100%;margin-top: -1em;margin-bottom: -1em;display: inline-block;\">");
//            companySigns.append("<div style=\"width: 100%;\">");
//            int i = 0;
//            for(String companyName : frameworkAgreementDO.getCompanyNames().split(",")){
//                i=i+1;
//                companyNames.append(StrUtil.format(company,i, companyName));
//                companySigns.append(StrUtil.format(companySign,i, companyName));
//            }
//            companyNames.append("</span>");
//            companySigns.append("</div>");
//        }

        // 开始构建HTML表格
        StringBuilder companyNames = new StringBuilder();
        StringBuilder companySigns = new StringBuilder();
        companyNames.append("<table style=\"border-collapse: collapse;border-color: initial;border-style: none;font-family: 黑体;line-height: 150%;font-size: 9.5pt;margin-top:-1em;\">"); // 添加表格边框
        companySigns.append("<table style=\"border-collapse: collapse;border-color: initial;border-style: none;font-family: 黑体;line-height: 150%;font-size: 9.5pt;\">"); // 添加表格边框
        String[] names = frameworkAgreementDO.getCompanyNames().split(",");
        // 遍历数组，但每次迭代处理两个元素（如果可能）
        String companyTd = "<td style=\"width: 267pt;padding: 0pt 5.4pt;border: none;\"><p class=\"MsoNormal\" style=\"margin-top: 5pt;margin-bottom: 5pt;line-height: 150%;\"><span style=\"font-size: 9.5pt;\">乙方（卖方{}）：</span><u><span style=\"font-size: 9.5pt;\">&nbsp;{}&nbsp;</span></u></p></td>";
        for (int i = 0; i < names.length; i += 2) {

            companyNames.append("<tr>");
            // 总是添加第一列
            companyNames.append(StrUtil.format(companyTd,i+1, names[i]));
            // 如果数组长度允许，则添加第二列
            if (i + 1 < names.length) {
                companyNames.append(StrUtil.format(companyTd,i+2, names[i + 1]));
            }
            companyNames.append("</tr>");


            companySigns.append("<tr>");
            // 总是添加第一列
            companySigns.append(StrUtil.format(companyTd,i+1, names[i]));
            // 如果数组长度允许，则添加第二列
            if (i + 1 < names.length) {
                companySigns.append(StrUtil.format(companyTd,i+2, names[i + 1]));
            }
            companySigns.append("</tr>");
            if (i + 1 < names.length) {
                companySigns.append("<tr style=\"height: 113.4000pt;\"><td style=\"width: 267.0500pt;border: none;\"><p class=\"MsoNormal\" style=\"\" align=\"center\"><span style=\"font-size: 9.5pt;\">（合同章）</span></p></td><td style=\"width: 267.0500pt;border: none;\"><p class=\"MsoNormal\" style=\"\" align=\"center\"><span style=\"font-size: 9.5pt;\">（合同章）</span></p></td></tr>");
            }else{
                companySigns.append("<tr style=\"height: 113.4000pt;\"><td style=\"width: 267.0500pt;border: none;\"><p class=\"MsoNormal\" style=\"\" align=\"center\"><span style=\"font-size: 9.5pt;\">（合同章）</span></p></td></tr>");
            }
        }
        companyNames.append("</table>"); // 结束表格

        companySigns.append("</table>"); // 结束表格

        param.put("公司信息",StringUtils.nvl(companyNames, ""));
//        param.put("公司签章",StringUtils.nvl(companySigns, ""));
        param.put("公司签章",StringUtils.nvl(companySigns, ""));

        //客户信息
        param.put("客户名称",StringUtils.nvl(clientDO.getClientName(), ""));
        param.put("客户简称",StringUtils.nvl(clientDO.getCalledForShort(), ""));
        param.put("客户电话",StringUtils.nvl(clientDO.getPhone(), ""));
        param.put("客户传真",StringUtils.nvl(clientDO.getFaxes(), ""));
        param.put("客户街道",StringUtils.nvl(clientDO.getStreet(), ""));
        param.put("客户法定代表",StringUtils.nvl(clientDO.getLegalPerson(), ""));
        param.put("客户委托代表",StringUtils.nvl(clientDO.getProxy(), ""));
        param.put("客户开户银行",StringUtils.nvl(clientDO.getBankName(), ""));
        param.put("客户开户账号",StringUtils.nvl(clientDO.getBankAccount(), ""));
        param.put("客户QQ",StringUtils.nvl(clientDO.getQqNumber(), ""));
        param.put("客户微信",StringUtils.nvl(clientDO.getWeChatNumber(), ""));
        param.put("客户收票地址",StringUtils.nvl(clientDO.getCollectionAddress(), ""));
        param.put("客户接收人姓名",StringUtils.nvl(clientDO.getReceiverName(), ""));
        param.put("客户接收人职务",StringUtils.nvl(clientDO.getReceiverDuty(), ""));
        param.put("客户接收人电话",StringUtils.nvl(clientDO.getReceiverPhone(), ""));
        param.put("街道2", StringUtils.nvl(clientDO.getStrSuppl1(), ""));
        param.put("街道3", StringUtils.nvl(clientDO.getStrSuppl2(), ""));
        //

        return param;
    }
    public static String sequenceCode(Integer maxNum, Long count) {  // 如生成001这种，maxNum为1000  0001的话maxNum则为10000，count则是我们从数据库中查询的总数

        String strNum = String.valueOf(maxNum + count);
        if (StringUtils.isEmpty(strNum) || 1 == strNum.length()) {
            return "";
        }
        return strNum.substring(1);
    }

    public static void main(String[] args) {
//        System.out.println("2024-11-04".substring(2,4));
        System.out.println(sequenceCode(10000, 0L));
    }
}